<?php
/*
 * @Author: lokei
 * @Date: 2022-08-20 17:03:15
 * @LastEditors: lokei
 * @LastEditTime: 2022-08-21 09:08:44
 * @Description: 
 */

namespace App\Http\Controllers\Scrm\Qiwei;

use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Scrm\Qiwei\Common;
use App\Models\Scrm\Department\DepartmentModel;
use GuzzleHttp;

class DepartmentController extends Controller
{

    public function sync()
    {
        $http = new GuzzleHttp\Client;
        $params = [
            'access_token' => Common::getAccessToken()
        ];
        $response = $http->get('https://qyapi.weixin.qq.com/cgi-bin/department/simplelist', [
            'query' => $params
        ]);
        $result = json_decode($response->getBody(), true);
        if (array_key_exists('errcode', $result) && $result['errcode'] != 0) {
            $res = ResultTool::fail();
            $res['errorCode'] = $result['errcode'];
            $res['errorMsg'] = $result['errmsg'];
            return $res;
        } else {
            $department_ids = $result['department_id'];
            $qw_ids = [];
            foreach ($department_ids as $qw_id) {
                array_push($qw_ids, $qw_id['id']);
            }
            $departments_list = DepartmentModel::get();
            $exists_qw_ids = [];
            foreach ($departments_list as $department) {
                if (!in_array($department->qw_id, $qw_ids)) {
                    DepartmentModel::where('id', '=', $department->id)->delete();
                } else {
                    array_push($exists_qw_ids, $department->qw_id);
                }
            }
            foreach ($department_ids as $qw_id) {
                if (!in_array($qw_id['id'], $exists_qw_ids)) {
                    $department = new DepartmentModel();
                    $department->qw_id = $qw_id['id'];
                    $department->parentid = $qw_id['parentid'];
                    $department->order = $qw_id['order'];
                    $department->save();
                }
            }
        }
        return ResultTool::success();
    }
}
